package org.smart4j.chapter.helper;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smart4j.framework.util.CollectionUtil;
import org.smart4j.framework.util.DBUtil;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.SQLException;
import java.util.*;

/**
 * Created by chinalin on 2017/3/14.
 * 数据库操作助手类
 */
public class DatabaseHelper {
    private static final Logger LOGGER = LoggerFactory.getLogger(DatabaseHelper.class);

    private static final QueryRunner QUERY_RUNNER ;

//    private static final ThreadLocal<Connection> CONNECTION_HOLDER ;
//
//    private static final BasicDataSource DATA_SOURCE ;

    /**
     * 读取jdbc参数
     */
    static{
//        CONNECTION_HOLDER = new ThreadLocal<Connection>() ;
        QUERY_RUNNER = new QueryRunner() ;

//        Properties conf = PropsUtil.loadProps("config.properties") ;
//        String driver = conf.getProperty("jdbc.driver") ;
//        String url = conf.getProperty("jdbc.url") ;
//        String username = conf.getProperty("jdbc.username") ;
//        String password = conf.getProperty("jdbc.password") ;

//        System.out.println("url:" + url);

//        DATA_SOURCE = new BasicDataSource() ;
//        DATA_SOURCE.setDriverClassName(driver);
//        DATA_SOURCE.setUrl(url);
//        DATA_SOURCE.setUsername(username);
//        DATA_SOURCE.setPassword(password);
       /* try{
            Class.forName(DRIVER) ;
        } catch (ClassNotFoundException e){
            LOGGER.error("can not load jdbc driver" , e);
        }*/
    }

    /**
     * 获取数据库连接
     */
//    public static Connection getConnection(){
//        Connection conn = CONNECTION_HOLDER.get() ;
//        if (conn == null){
//            try{
//                conn = DATA_SOURCE.getConnection();
//            }catch (SQLException e){
//                LOGGER.error("get connection failure", e);
//                throw new RuntimeException(e) ;
//            } finally {
//                CONNECTION_HOLDER.set(conn);
//            }
//        }
//        return conn ;
//    }

    /**
     * 关闭数据库连接
     */
/*    public static void closeConnection(){
        Connection conn = CONNECTION_HOLDER.get() ;
        if (conn != null){
            try {
                conn.close();
            }catch (SQLException e){
                LOGGER.error("close connection failure",e);
                throw new RuntimeException(e) ;
            }finally {
                CONNECTION_HOLDER.remove();
            }
        }

    }*/

    /**
     * 查询字段
     * ScalarHandler
     * 返回多条用 ColumnListHandler
     */
    public static <T> T query(String sql ,Object... params){
        T result ;
        try {
            result = QUERY_RUNNER.query(DBUtil.getConnection(),sql, new ScalarHandler<T>(),params);
        }catch (SQLException e){
            LOGGER.error("query result failure", e);
            throw new RuntimeException(e) ;
        }
        return result ;
    }

    /**
     * 查询字段集合
     * ScalarHandler
     * 返回多条用 ColumnListHandler
     */
    @SuppressWarnings("unchecked")
    public static <T> Set<T>  querySet(String sql ,Object... params){
        Set<T> result = new HashSet<T>();
        try {
//            System.out.println("使用Array处理多行记录！");
            List<Object[]> arraylist = QUERY_RUNNER.query(DBUtil.getConnection(), sql,new ArrayListHandler());
            Iterator<Object[]> itr = arraylist.iterator();
            while (itr.hasNext()){
                Object[] a = itr.next();
                result.add((T)a[0]) ;
            }
        }catch (SQLException e){
            LOGGER.error("query Set<T> failure", e);
            throw new RuntimeException(e) ;
        }
        return result ;
    }

    /**
     *查询实体列表
     */
    public static <T> List<T> queryEntityList(Class<T> entityClass, String sql, Object... params){
        List<T> entityList ;
        try{
//            Connection conn = getConnection() ;
            entityList = QUERY_RUNNER.query(DBUtil.getConnection(),sql,new BeanListHandler<T>(entityClass),params);
        }catch (SQLException e){
            LOGGER.error("query entity list failure" , e);
            throw new RuntimeException(e);
        }
        return entityList ;
    }


    /**
     * 查询实体
     */
    public static <T> T queryEntity(Class<T> entityClass, String sql,Object... params){
        T entity ;
        try {
//            Connection conn = getConnection() ;
            entity = QUERY_RUNNER.query(DBUtil.getConnection(), sql ,new BeanHandler<T>(entityClass), params) ;
        }catch (SQLException e){
            LOGGER.error("query entity failure", e);
            throw new RuntimeException(e) ;
        }
        return entity ;
    }

    /**
     * 执行查询语句
     */
    public static List<Map<String,Object>> executeQuery(String sql ,Object... params){
        List<Map<String,Object>> result ;
        try {
//            Connection conn = getConnection() ;
            result = QUERY_RUNNER.query(DBUtil.getConnection(),sql,new MapListHandler(),params) ;
        }catch (Exception e){
            LOGGER.error("execute query failure", e);
            throw new RuntimeException(e) ;
        }
        return result ;
    }

    /**
     * 执行更新语句(包括 update、insert、delete)
     */
    public static int executeUpdate(String sql ,Object...params){
        int rows = 0 ;
        try {
//            Connection conn = getConnection() ;
            rows = QUERY_RUNNER.update(DBUtil.getConnection(),sql,params);
        }catch (SQLException e){
            LOGGER.error("execute update failure" ,e );
            throw new RuntimeException(e) ;
        }
        return rows ;
    }

    /**
     * 插入实体
     */
    public static <T> boolean insertEntity(Class<T> entityClass,Map<String,Object> fieldMap){
        if (CollectionUtil.isEmpty(fieldMap)){
            LOGGER.error("can not insert entity: fieldMap is empty");
            return false ;
        }
        String sql = "INSERT INTO " + getTableName(entityClass) ;
        StringBuilder columns = new StringBuilder("(") ;
        StringBuilder values = new StringBuilder("(") ;
        for (String fieldname : fieldMap.keySet()){
            columns.append(fieldname).append(", ");
            values.append("?, ") ;
        }
        columns.replace(columns.lastIndexOf(", "), columns.length(), ")") ;
        values.replace(values.lastIndexOf(", "), values.length(),")") ;
        sql += columns + " VALUES " + values ;

        Object[] params = fieldMap.values().toArray() ;
        return executeUpdate(sql, params) == 1 ;
    }

    /**
     * 更新实体
     */

    public static <T> boolean updateEntity(Class<T> entityClass,long id ,Map<String,Object> fieldMap){
        if (CollectionUtil.isEmpty(fieldMap)){
            LOGGER.error("can not update entity: fieldMap is empty");
            return false ;
        }
        String sql = "UPDATE " + getTableName(entityClass) + " SET ";
        StringBuilder columns = new StringBuilder() ;
        for (String fieldname : fieldMap.keySet()){
            columns.append(fieldname).append("=?, ");
        }
        sql += columns.substring(0, columns.lastIndexOf(", ")) + " WHERE id=?" ;
        List<Object> paramList = new ArrayList<Object>();
        paramList.addAll(fieldMap.values()) ;
        paramList.add(id);
        Object[] params = paramList.toArray() ;
        return executeUpdate(sql, params) == 1 ;
    }

    /**
     * 删除实体
     */
    public static <T> boolean deleteEntity(Class<T> entityClass ,long id){
        String sql = "DELETE FROM " + getTableName(entityClass) + " WHERE id=?";
        return executeUpdate(sql,id) == 1 ;
    }

    private static String getTableName(Class<?> entityClass){
        return entityClass.getSimpleName();
    }

    /**
     * 执行 SQL 文件
     */
    public static void executeSqlFile(String filePath){
        InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(filePath);
        BufferedReader reader = new BufferedReader(new InputStreamReader(is)) ;
        try {
            String sql ;
            while ((sql = reader.readLine()) != null){
                executeUpdate(sql) ;
            }
        }catch (Exception e){
            LOGGER.error("execute sql file failure ",e );
            throw new RuntimeException(e) ;
        }
    }
}
